package com.qf.web.controller;

import com.alibaba.druid.util.StringUtils;
import com.qf.domain.*;
import com.qf.service.AddressService;
import com.qf.service.CartService;
import com.qf.service.GoodsService;
import com.qf.service.OrderService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.CartServiceImpl;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.utils.RandomUtil;
import com.qf.utils.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * projectName:myxiaomi
 * author:lcy
 * time:2024/4/17 16:29
 * description:
 */
@WebServlet("/orderservlet")
public class OrderServlet extends BaseServlet {

    //http://localhost:8080/orderservlet?method=getOrderView
    public String getOrderView(HttpServletRequest request, HttpServletResponse response){
        User user= (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }

        try {
            CartService cartService=new CartServiceImpl();
            List<Cart> cartList = cartService.selectByUserId(user.getId());

            AddressService addressService=new AddressServiceImpl();
            List<Address>addressList= addressService.selectByUserId(user.getId());
            request.setAttribute("cartList",cartList);
            request.setAttribute("addList",addressList);
            return "/order.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "预览账单失败");
            return "/message.jsp";
        }
    }

    //http://localhost:8080/orderservlet?method=addOrder&aid=10
    public String addOrder(HttpServletRequest request, HttpServletResponse response){
        User user= (User) request.getSession().getAttribute("user");
        if(user == null){
            return "redirect:/login.jsp";
        }
        String aid = request.getParameter("aid");
        if(StringUtil.isEmpty(aid)){
            request.setAttribute("msg", "地址id不能为空");
            return "/message.jsp";
        }

        try {
            CartService cartService=new CartServiceImpl();
            List<Cart> cartList = cartService.selectByUserId(user.getId());
            if (cartList == null||cartList.size()==0) {
                request.setAttribute("msg","购物车不能为空");
                return "/message.jsp";
            }
            BigDecimal money=new BigDecimal(0);
            for (Cart cart : cartList) {
                money=money.add(cart.getMoney());
            }
            String oid= RandomUtil.createOrderId();
            Order order=new Order(oid,user.getId(),money,"1",new Date(),Integer.parseInt(aid));
            OrderService orderService =new OrderServiceImpl();
            orderService.submitOrder(order,cartList);
            request.setAttribute("order",order);
            return "/orderSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","添加订单失败："+e.getMessage());
            return "/message.jsp";
        }
    }


    //orderservlet?method=getOrderList
    public String getOrderList(HttpServletRequest request, HttpServletResponse response){
        User user= (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        try {
            OrderService orderService=new OrderServiceImpl();
            List<Order>orderList=orderService.selectByUserId(user.getId());
            request.setAttribute("orderList", orderList);
            return "/orderList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","查询订单失败"+e.getMessage());
            return "/message.jsp";
        }
    }


    //http://localhost:8080/orderservlet?method=getOrderDetail&oid=202404181634148047197704
    public String getOrderDetail(HttpServletRequest request, HttpServletResponse response){
        User user= (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        String oid = request.getParameter("oid");
        if(StringUtil.isEmpty(oid)){
            request.setAttribute("msg", "订单编号不能为空");
            return "/message.jsp";
        }
        try {
            OrderService orderService=new OrderServiceImpl();
            Order order=orderService.selectByOid(oid);
            List<OrderDetail>orderDetails=orderService.selectOrderDetail(oid);
            request.setAttribute("order", order);
            request.setAttribute("orderDetails", orderDetails);
            return "/orderDetail.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","查询订单详情失败："+e.getMessage());
            return "/message.jsp";
        }
    }


    //--------------------------------------后台-------------------------------------


    //orderservlet?method=sendOrder?oid="+id;
    //orderservlet?method=searchOrder&id="+id+"&status="+status;
    public String searchOrder(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("UTF-8");
        String username = request.getParameter("username");
        String status = request.getParameter("status");
        //String oid = request.getParameter("oid");
        String id = request.getParameter("id");
        //System.out.println("username="+username);
        System.out.println("id="+id);
        System.out.println("status="+status);

        OrderService orderService=new OrderServiceImpl();
        List<Object> params =new ArrayList<>();
        StringBuilder where =new StringBuilder(" where 1=1 ");
        if(!StringUtils.isEmpty(id)){
            where.append(" and id=? ");
            params.add(id);
        }
        if(!StringUtils.isEmpty(status)){
            where.append(" and status=? ");
            params.add(status);
        }
        try {
            List<Order> orderList = orderService.selectAll(where.toString(),params);
            request.setAttribute("orderList",orderList);
            return  "admin/showAllOrder.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "查看管理失败："+e.getMessage());
            return "admin/message.jsp";
        }
    }

    //orderservlet?method=findOrder('${order.id/}')" >发货</a>&nbsp;
    ///orderservlet?method=sendOrder&id=${order.id}
    public String sendOrder(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");
        System.out.println("id = " + id);
        if(StringUtil.isEmpty(id)){
            request.setAttribute("msg", "商品编号不为空");
            return "/admin/message.jsp";
        }
        try {
            OrderService orderService=new OrderServiceImpl();
            //orderService.deleteByOId(id);
            orderService.updateStatusById3(id);
            return "redirect:/orderservlet?method=searchOrder";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "发货（删除）失败："+e.getMessage());
            return "admin/message.jsp";
        }
    }


    //orderservlet?method=PayOrder&id=${order.id}" >去支付</a>
    public String PayOrder(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");
        System.out.println("id = " + id);
        if(StringUtil.isEmpty(id)){
            request.setAttribute("msg", "商品编号不为空");
            return "/admin/message.jsp";
        }
        try {
            OrderService orderService=new OrderServiceImpl();
            orderService.updateStatusById2(id);
            return "redirect:/orderservlet?method=searchOrder";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "后台支付（删除）失败："+e.getMessage());
            return "admin/message.jsp";
        }
    }

    //<a href="/orderservlet?method=harvestOrder&id=${order.id}" >已收货</a>
    public String harvestOrder(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");
        System.out.println("id = " + id);
        if(StringUtil.isEmpty(id)){
            request.setAttribute("msg", "商品编号不为空");
            return "/admin/message.jsp";
        }
        try {
            OrderService orderService=new OrderServiceImpl();
            orderService.updateStatusById4(id);
            return "redirect:/orderservlet?method=searchOrder";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "后台支付（删除）失败："+e.getMessage());
            return "admin/message.jsp";
        }
    }
}


